package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.RegionQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.utils.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/region")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @RequestMapping("list")
    public String list(@ModelAttribute("qo") QueryObject qo, Model model){

        return "/region/list";
    }

    @RequestMapping("getRegion")
    @ResponseBody
    public Object getRegion(@ModelAttribute("qo") RegionQueryObject qo){
        List<Region> list=regionService.selectRegionByParentId(qo);
        //创建一个Mlist用来存放对应数据的map
        List<Map<String,Object>> mList = new ArrayList<Map<String, Object>>();
        for (Region region : list) {
            Map<String, Object> map = region.changeToMap();
            mList.add(map);
        }
        return mList;
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region region){
        JSONResult result = new JSONResult();
        try{
            regionService.saveOrUpdate(region);
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }


    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id){
        regionService.deleteById(id);
        return  new JSONResult();
    }
}
